package com.fuja.fumo.ui;
import org.apache.log4j.Logger;

import com.fuja.fumo.handler.MockHandler;
import com.fuja.fumo.model.Option;
import com.fuja.fumo.model.Question;
import com.fuja.swf.ui.UIUtil;
import superwaba.ext.xplat.ui.MultiEdit;
import waba.fx.*;
import waba.io.File;
import waba.sys.*;
import waba.ui.*;
import waba.util.Vector;
/**
 * @see superwaba.samples.app.sales.ui.product.NewProduct
 * @author marcelo_adamatti
 *
 */
public class UIQuestion extends Window {
	private static Logger log = Logger.getLogger(UIQuestion.class);
	//OTHER
	private boolean showAnswer=true;
	private int current=0;
	public Vector questions;
	//LAYOUT
	private Label lblObjective = new Label("",LEFT);
	private MultiEdit meQuestion = new MultiEdit("",7,0);
	private PushButtonGroup btnNavegacao = new PushButtonGroup(new String[]{"<<"," < "," > ",">>"}, -1,1);
	private RefreshButton btnShow = new RefreshButton("Answer");
	private RefreshButton  btnMark = new RefreshButton ("Mark");
	private Button btnGraph = new Button("Graph");
	private Button btnExport = new Button("Export");
	
	private Vector options = new Vector();	 
	
	private UIQuestion(){
		super();
		log.info("Create UIQuestion..."); 
		lblObjective.setBackColor(Color.BLACK);
	    lblObjective.setForeColor(Color.WHITE);
	}
	public UIQuestion(File file){
		this();		
		
		MockHandler handler = new MockHandler();
		if (!file.exists())
			UIUtil.showMsg("Error","File not found!");
		try {
			handler.tokenize(file);
		} catch (Exception e){
			e.printStackTrace();
			String aux = Convert.insertLineBreak(Settings.screenWidth-10, '|', fm,e.getMessage());
			UIUtil.showMsg("Error","Error processing file: " + aux);
		}
		questions = handler.getQuestions();
		
	}
	public UIQuestion(String path){
		this();
		this.questions =loadQuestions(path);
	}
	public UIQuestion(Vector questions){
		this();
	    this.questions = questions;
	}	 
	private Vector loadQuestions(String path){
		log.debug("loadQuestions ");
		
		byte [] xml = Vm.getFile(path);
		MockHandler handler = new MockHandler();
		log.debug("Load ok!");
		if (xml==null)
			UIUtil.showMsg("Error","File not found: " + path);
		try {
			handler.tokenize(xml);
		} catch (Exception e){
			UIUtil.showMsg("Error","Error processing file: " + e.getMessage());
		}
		return handler.getQuestions();
	}

	public void onStart(){
		removeAll();
		buidUI();
	}
	private void removeAll(){
		Control [] controls = new Control[]{meQuestion,btnGraph,btnMark, btnNavegacao,lblObjective,btnShow,btnExport};
		for (int i=0;i< controls.length;i++)
			remove(controls[i]);
		
		for (int i=0;i< options.size();i++)
			remove((Button)options.items[i]);
	}
	private void buidUI(){
		Question q = (Question) questions.items[current];		
		Question lastQ = (Question) questions.items[questions.size()-1];
		
		lblObjective.setText(q.getId() + "/"+ lastQ.getId() + ") " + q.getObjective());
		add(lblObjective);
		lblObjective.setRect(LEFT,TOP, Settings.screenWidth, PREFERRED);
		
		add(btnShow, LEFT+1,AFTER);
		add(btnGraph,AFTER+1,SAME);
		add(btnExport,AFTER+1,SAME);
		
		btnMark.setText(q.isMarked()?"Unmark" :"Mark");
		add(btnMark,AFTER+1,SAME);		
		
		add(btnNavegacao,RIGHT-1,SAME);
		btnNavegacao.setFocusLess(true);
		
		meQuestion.setText(q.getDescription());
		add(meQuestion,LEFT,AFTER);

		addOptions(q);		
		repaintNow();
		
	}
	private void addOptions(Question q) {
		options.removeAllElements();
		for (int i=0;i< q.getOptions().size();i++){
			Option o = (Option) q.getOptions().items[i];
			
			//ADD BUTTON IN SCREEN
			String aux = Convert.insertLineBreak(Settings.screenWidth-10, '|', fm,o.getDescription());
			OptionButton ob = new OptionButton(aux);
			ob.option = o;
			add(ob);
			ob.setRect(CENTER,AFTER +5, Settings.screenWidth-5, PREFERRED);
			if (o.getValue() && showAnswer){
				ob.setForeColor(Color.YELLOW);
			}else {
				ob.setForeColor(Color.BLACK);
			}				
			
			//SAVE REFERENCE
			options.addElement(ob);
		}
	}
	private void navigationEvent(int index){
		switch (index) {
			case 0: //first
				if (current != 0)
					current=0;
				break;
			case 1:  //prev
				if (current > 0)
					current--;
				break;
			case 2: //next
				if (current < questions.size()-1)
					current++;				
				break;
			case 3: //last
				if (current != questions.size()-1)
					current=questions.size()-1;
				break;
		}
	}
	public void onEvent(Event e) {
		Question question = (Question) questions.items[current];
		if ((e.target == btnNavegacao) && (e.type==ControlEvent.PRESSED)){
			navigationEvent(btnNavegacao.getSelected());
		} else if ((e.target instanceof OptionButton) && (e.type==ControlEvent.PRESSED)){
			OptionButton ob = (OptionButton) e.target;
			String msg="No description";
			if (!ob.option.getReason().equals(""))
				msg = Convert.insertLineBreak(Settings.screenWidth-10, '|', fm,ob.option.getReason());
			if (fm.getTextWidth(ob.label)>Settings.screenWidth-10){
				int value = UIUtil.showMsg("Question",ob.label,new String[]{"Correct","Wrong","Cancel"});
								
				if ((ob.option.getValue() && value==0)
					|| (!ob.option.getValue() && value==1)
				){
					question.setAnswered(true);
					UIUtil.showMsg("Answer: true",msg);
				} else if (value!=2){
					question.setAnswered(true);
					UIUtil.showMsg("Answer: false",msg);
					question.setError(true);
				}
			} else {
				question.setAnswered(true);
				UIUtil.showMsg("Answer: " + ob.option.getValue(), msg);
				if (!ob.option.getValue())
					question.setError(true);
			}
			
		} else if (e.target==btnShow){
			showAnswer=!showAnswer;			
		} else if (e.target == btnMark){
			question.setMarked(!question.isMarked());
		} else if ((e.target== btnGraph) && (e.type==ControlEvent.PRESSED)){
			showGraph();
		} else if ((e.target==btnExport)&& (e.type==ControlEvent.PRESSED)){
			showExport();
		}
		if ((e.target instanceof RefreshButton)|| (e.target==btnNavegacao)){
			removeAll();
			buidUI();
		}
		if (e.type==ControlEvent.PRESSED)
			repaintNow();
	}
	public void showExport(){
		UIExport exp = new UIExport(questions);
		UIUtil.swap(exp);
	}
	public void showGraph(){
		UIResult graph = new UIResult(questions);
		UIUtil.swap(graph);
	}
	private class RefreshButton extends Button{
		public RefreshButton(String text) {
			super(text);
		}
	}
	private class OptionButton extends Button{
		public String label;
		public Option option;
		public OptionButton(String label) {
			super("");
			
			this.label = label;
			if (fm.getTextWidth(label)>Settings.screenWidth - 10){
				String aux = label;
				while (fm.getTextWidth(aux + "...")>Settings.screenWidth - 10){
					aux = aux.substring(0,aux.length()-2);
				}
				this.setText(aux + "...");
			}else {				
				this.setText(label);
			}
		}	
	}
}


